<?php
/**
 * [KeCms] Copyright (c) 2017 kecms.cn
 * [Author] King east ( 1207877378@qq.com )
 */

namespace app\admin\controller;


use app\admin\model\AdminRule;
use app\admin\model\AdminRuleAccess;
use ke\Controller;
use think\Cache;

class MenuController extends Controller
{
    public function lists()
    {
        $type=input('get.type');
        switch ($type){
            case 1:
                $list=AdminRule::order('showorder','asc')->with('parent')->select()
                    ->toArray();
                $this->result(['list'=>list_to_tree($list,'id','parent_id')]);
            default:
                return $this->fetch();
        }
    }

    /**
     * 保存
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function save()
    {
        $form=getForm();
        $result=$this->validate($form,[
            'title|中文标题'=>'require|max:20',
            'name|英文标题'=>'require|max:20',
            'controller|权限规则'=>'require|max:50',
            'icon|图标'=>'max:20'
        ]);
        if($result!==true){
            $this->error($result);
        }
        if(empty($form['id'])){
            $data=new AdminRule();
        }else{
            $data=AdminRule::where('id',$form['id'])->find();
            if(!$data){
                $this->error('菜单不存在或已经删除');
            }
        }
        $data->name=$form['name'];
        $data->title=$form['title'];
        $data->controller=$form['controller'];
        $data->icon=isset($form['icon']) ? $form['icon'] : '';
        $data->parent_id=empty($form['parent_id']) ? 0 : $form['parent_id'];
        $data->showorder=empty($form['showorder']) ? 0 : $form['showorder'];
        $data->hidden=empty($form['hidden']) ? 0 : $form['hidden'];
        if($data->save()){
            // 清除菜单缓存
            $list=AdminRuleAccess::where('rule_id',$data->id)->group('role_id')->select();
            foreach ($list as $g){
                Cache::rm('adminMenuList/'.$g->role_id);
                Cache::rm('adminRuleAccess/'.$g->role_id);
            }
            unset($list);
            $this->result($data->toArray());
        }else{
            $this->error('数据无变化，无需修改。');
        }

    }


    /**
     * 删除
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function delete()
    {
        $id=input('get.id');
        if(empty($id)){
            $this->error('参数错误');
        }
        $data=AdminRule::where('id',$id)->whereOr('parent_id',$id)->select();
        $n=0;
        foreach ($data as $g){
            if($g->delete()){
                $n++;
            }
        }
        if($n){
            $this->success('成功删除'.$n.'条');
        }else{
            $this->error('删除失败');
        }
    }
}